import 'antd/dist/antd.less';
import {BrowserRouter, Navigate, Route, Routes} from "react-router-dom"
import {RouterMap} from "./config/route.config";
import BasicLayout from "./layouts/BasicLayout";
import {useDispatch} from "react-redux"
import {toggleTheme, toggleColor, toggleLayoutMode} from "./store/modular/app"
import { setToken } from "./store/modular/user";
import storage from "store";
import {ACCESS_TOKEN, DEFAULT_COLOR, DEFAULT_LAYOUT_MODE, DEFAULT_THEME} from "./store/mutation-types";
import asyncComponent from "./utils/asyncComponent";
import {treeToArray} from "./utils/utils";
import {useEffect} from "react";

const generateRouter = (list) => {
    return (
        <>
            {
                list.map(item => {
                    if (!storage.get(ACCESS_TOKEN)){
                        item.element = <Navigate to="/user/login" replace />
                    }
                    if (item.children) {
                        return (
                            <Route key={item.key} path={item.rule} element={item.element}>{generateRouter(item.children)}</Route>
                        )
                    } else {
                        return <Route key={item.key} index={item.index ? true : false} path={item.rule} element={item.element}/>
                    }
                })
            }
        </>
    )
}

const RouterMatch = () => {
    const routes = treeToArray(RouterMap)
    const {pathname} = new URL(window.location.href)
    const match = routes.find(item => item.jump === pathname)
    if (!match && pathname !== '/404' && pathname !== '/user/login'){
        window.location.href = '/404'
    }
}

function App() {
    const dispatch = useDispatch()
    useEffect(()=>{
        RouterMatch()
        if (storage.get(ACCESS_TOKEN)){
            dispatch(setToken(storage.get(ACCESS_TOKEN)))
            dispatch(toggleTheme(storage.get(DEFAULT_THEME)))
            dispatch(toggleColor(storage.get(DEFAULT_COLOR)))
            dispatch(toggleLayoutMode(storage.get(DEFAULT_LAYOUT_MODE)))
        }
    })

    return (
        <BrowserRouter>
            <Routes>
                <Route path='/' element={<BasicLayout/>}>
                    {generateRouter(RouterMap)}
                </Route>
                <Route path='/user/login' element={asyncComponent(()=>import('@/views/user/Login'))}/>
                <Route path='/403' element={asyncComponent(()=>import('@/views/exception/403'))}/>
                <Route path='/404' element={asyncComponent(()=>import('@/views/exception/404'))}/>
                <Route path='/500' element={asyncComponent(()=>import('@/views/exception/500'))}/>
            </Routes>
        </BrowserRouter>
    )
}

export default App;
